import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import { NButton, NForm, NFormItem, NInput, NSpin, useNotification } from 'naive-ui'
import { defineComponent, ref } from 'vue'
// import { useRouter } from 'vue-router'

type LoginForm = {
  username: string
  password: string
}

const LoginPage = defineComponent(() => {
  const form = ref<LoginForm>({ username: 'admin', password: 'admin1' })
  // const router = useRouter()
  const loginLoading = ref(false)
  const notification = useNotification()
  const userStore = useUserStore()
  // todo 跳转路由
  function handleGoPath(path: string) {
    router.push({ path })
  }

  // todo 登录
  async function handleLogin() {
    loginLoading.value = true
    const [err] = await userStore.login(form.value)
    loginLoading.value = false
    if (err) return notification.error({ content: err, title: '登录失败', duration: 3000 })
    notification.success({ content: '欢迎', title: '登录成功', duration: 3000 })
    handleGoPath('/home')
  }

  return () => (
    <NSpin show={loginLoading.value}>
      <div class="px-10 py-5 shadow-2xl rounded bg-white">
        <p class="italic text-center mb-3 text-xl font-black">Template for TS</p>
        <NForm class="w-72" show-require-mark={false} model={form.value}>
          <NFormItem
            label="用户名"
            rule={{ required: true, message: '请先输入用户名' }}
            path="form.username"
          >
            <NInput
              v-model:value={form.value.username}
              placeholder="输入用户名"
              type="text"
            ></NInput>
          </NFormItem>
          <NFormItem
            label="密码"
            rule={{ required: true, message: '请先输入密码' }}
            path="form.password"
          >
            <NInput
              v-model:value={form.value.password}
              placeholder="输入密码"
              type="password"
            ></NInput>
          </NFormItem>
          <NButton block type="primary" loading={loginLoading.value} onClick={handleLogin}>
            登&nbsp;&nbsp;&nbsp;录
          </NButton>
          <p class="flex justify-between mt-2">
            <NButton tag="a" text>
              忘记密码？
            </NButton>
            <NButton tag="a" text onClick={() => handleGoPath('/reset')}>
              没有账号？点这里
            </NButton>
          </p>
        </NForm>
      </div>
    </NSpin>
  )
})

export default LoginPage
